#include <string>
#include <iostream>

#include "ConnectionHandlerHTTPS.hpp"
#include "Logger.hpp"
#include "SSLWrapper.hpp"

ConnectionHandlerHTTPS::ConnectionHandlerHTTPS(SSL_CTX* globalContext) : ConnectionHandler(), globalContext(globalContext) {
}

ConnectionHandlerHTTPS::ConnectionHandlerHTTPS(TCPConnection& connection) : ConnectionHandler(connection) {
}

void ConnectionHandlerHTTPS::handle() {
	SSL* ssl = SSLWrapper::newConnection(globalContext);
	BIO* bio = SSLWrapper::sessionToChannel(connection->getFD(), ssl, false);

	LOGSTRM(Logger::INFO, "Peer Certificate: " << SSLWrapper::sslPeerCertificateToString(ssl));

	std::string line;
	line = SSLWrapper::readLineFromChannel(bio);

	SSLWrapper::writeLineToChannel(bio, "HTTP/1.0 200 OK\r\n");
	SSLWrapper::writeLineToChannel(bio, "\r\n");
	SSLWrapper::writeLineToChannel(bio, "<html>");
	SSLWrapper::writeLineToChannel(bio, "	<body>\n");
	SSLWrapper::writeLineToChannel(bio, "		<center><h1>Hello World</h1></center>\n");
	SSLWrapper::writeLineToChannel(bio, "		<hr>\n");
	SSLWrapper::writeLineToChannel(bio, "		<p>This is an http<b>S</b> session, ");
	SSLWrapper::writeLineToChannel(bio, connection->getRemoteStr());
	SSLWrapper::writeLineToChannel(bio, "</p>");
	SSLWrapper::writeLineToChannel(bio, "	</body>\n");
	SSLWrapper::writeLineToChannel(bio, "</html>\n");

	SSLWrapper::closeSession(ssl);

	connection->close();
}

ConnectionHandlerHTTPS::~ConnectionHandlerHTTPS() {
}

